
package com.xayq.orap.oauth.token;


import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xayq.orap.oauth.MyOAuthTokenRequest;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

@Component
public class OAuthTokenHandleDispatcher {

    private static final Logger LOG = LoggerFactory.getLogger(OAuthTokenHandleDispatcher.class);
    
    @Autowired
    protected AuthorizationCodeTokenHandler authorizationCodeTokenHandler;
    @Autowired
    protected PasswordTokenHandler passwordTokenHandler;
    @Autowired
    protected RefreshTokenHandler refreshTokenHandler;
    @Autowired
    protected ClientCredentialsTokenHandler clientCredentialsTokenHandler;

    private Map<String,AbstractOAuthTokenHandler> handlers = new HashMap<String,AbstractOAuthTokenHandler>();

//    private OAuthTokenRequest tokenRequest;
//    private HttpServletResponse response;

    public OAuthTokenHandleDispatcher() {
//        this.tokenRequest = tokenRequest;
//        this.response = response;

//        initialHandlers();
    }
    @PostConstruct
    private void initialHandlers() {
        handlers.put(GrantType.AUTHORIZATION_CODE.toString(),authorizationCodeTokenHandler);
        handlers.put(GrantType.PASSWORD.toString(),passwordTokenHandler);
        handlers.put(GrantType.REFRESH_TOKEN.toString(),refreshTokenHandler);
        handlers.put(GrantType.CLIENT_CREDENTIALS.toString(),clientCredentialsTokenHandler);

        LOG.debug("Initialed '{}' OAuthTokenHandler(s): {}", handlers.size(), handlers);
    }


    public void dispatch(MyOAuthTokenRequest tokenRequest, HttpServletResponse response) throws OAuthProblemException, OAuthSystemException {
        
        AbstractOAuthTokenHandler handler = handlers.get(tokenRequest.getGrantType());
        if(handler != null){
        	LOG.debug("Found '{}' handle OAuthTokenRequest: {}", handler, tokenRequest);
            handler.handle(tokenRequest, response);
            return;
        }
        throw new IllegalStateException("Not found 'OAuthTokenHandler' to handle OAuthTokenRequest: " + tokenRequest);
    }
}
